package com.polaris.live.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.ApiResponse
import com.polaris.live.common.network.getSuccessResult
import com.polaris.live.common.resp.ConfigPreResp
import com.polaris.live.common.util.LogExt
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.manager.DomainManager
import com.polaris.live.net.networkResettableManager
import com.polaris.live.net.userService
import com.polaris.live.utils.SetMapData
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlin.time.Duration.Companion.seconds

/**
 * 启动页的viewModel
 *
 * @author Created by 半仙 on 2023/8/15/015 17:11
 */
class WelcomeViewModel : BaseViewModel() {

    val configPreLiveData = MutableLiveData<ApiResponse<ConfigPreResp>>()

    fun config(isRetry: Boolean? = false) {
        viewModelScope.launch {
            //如果是重试需要重新获取域名
            if (isRetry == true) {
                val mainUrl = CacheUtil.getMainUrlFromKV()
                val currentUrl = ServerConfig.getServerUrl()
                //如果是一致的代表这个也有可能存在问题，需要重新获取
                val newCurrentUrl = if (mainUrl != null && mainUrl != currentUrl) {
                    mainUrl
                } else {
                    DomainManager.fetchMainUrl() ?: currentUrl
                }

                //如果的确是有新的，修改请求的base域名，然后重新请求
                if (newCurrentUrl != currentUrl) {
                    ServerConfig.updateCustomConfig(newCurrentUrl)
                    CacheUtil.saveCurrentUrl(newCurrentUrl)

                    networkResettableManager.reset()
                }

                LogExt.logI("--net", "retry config: mainUrl = $mainUrl, currentUrl = $currentUrl")
            } else {
                //默认异步更新
                DomainManager.domainWithAsync()
            }

            val resp = AppConfigManager.getConfigPre()
            val firstApp = resp == null
            if (!firstApp) {
                //如果不是第一次进去则直接异步请求post数据
                asyncFetchConfigPost()
            }

            val preResp = fetchConfigPre(isRetry)
            val preConfig = preResp.getSuccessResult()
            if (preConfig != null) {
                AppConfigManager.updateConfigPre(preConfig)

                if (firstApp) {
                    //否则等待pre成功在请求
                    asyncFetchConfigPost()
                }
            }

            configPreLiveData.value = preResp
        }
    }

    private suspend fun fetchConfigPre(isRetry: Boolean?): ApiResponse<ConfigPreResp> {
        return try {
            //第一次pre只给5秒防止卡死
            if (isRetry == true) {
                userService.configPre(SetMapData.genPreMap())
            } else {
                withTimeout(5.seconds) {
                    userService.configPre(SetMapData.genPreMap())
                }
            }
        } catch (t: Throwable) {
            ApiResponse.error(500, t.message ?: "network error")
        }
    }

    private fun asyncFetchConfigPost() {
        CoroutineScopeManager.defaultScope.launch {
            val postResp =
                userService.configPost(SetMapData.genPostMap()).getSuccessResult()
            if (postResp != null) {
                AppConfigManager.updateConfigPost(postResp)
            }
        }
    }
}